# -*- coding: latin-1 -*-
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.forms import *
from django.contrib.localflavor.ar.forms import *
from django.conf import settings

try:
	label_usuario = settings.LOGIN_USER_LABEL
	label_password = settings.LOGIN_PASSWORD_LABEL
except:
	label_usuario = "Usuario"
	label_password = "Nueva contraseña"
	
class CrearUsuarioForm(forms.ModelForm):
	username = forms.EmailField(label=label_usuario, max_length=200)
	password1 = forms.CharField(label=label_password, widget=forms.PasswordInput, help_text='Con esta contraseña podrá entrar en cualquier momento')
	password2 = forms.CharField(label="Confirmación de contraseña", widget=forms.PasswordInput)

	def titulo(self):
		return "Crear nuevo usuario"
		
	def help_text(self):
		return "Si ya se ha registrado, utilice el formulario de la parte superior de la página"

	class Meta:
		model = User
		fields = ("last_name", "first_name", "username", "password1", "password2")

	def clean_username(self):
		username = self.cleaned_data["username"]
		try:
			User.objects.get(username=username)
		except User.DoesNotExist:
			return username
		raise forms.ValidationError("Ese usuario ya está registrado")

	def clean_password2(self):
		password1 = self.cleaned_data.get("password1", "")
		password2 = self.cleaned_data["password2"]
		if password1 != password2:
			raise forms.ValidationError("Las contraseñas no coinciden")
		return password2

	def save(self, commit=True):
		user = super(CrearUsuarioForm, self).save(commit=False)
		user.set_password(self.cleaned_data["password1"])
		user.email = user.username
		if commit:
			user.save()
		return user

